package rush.edu.wechat.web.filter;

import com.alibaba.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import rush.edu.wechat.common.config.PublicConfig;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * DESC:拦截用户
 * USER:hmily
 * DATE:2018/1/31
 * TIME:20:42
 */
@Component
@ServletComponentScan
@WebFilter(filterName = "gateWay" ,urlPatterns = "/admin/**")
public class GateWayFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        //获取请求的uri
        String requestURI = httpRequest.getRequestURI();
        Map<String, String> annonUriMap = PublicConfig.annonUri;
        Collection<String> annonUri = annonUriMap.keySet();
        //放行
        if (annonUri.contains(requestURI)){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            HttpSession session = httpRequest.getSession();
            String token = (String)session.getAttribute("token");
            //
            if (StringUtils.isEmpty(token)){
                token = (String) RpcContext.getContext().get("token");
                if (StringUtils.isEmpty(token)){
                    return;
                }
            }
            Boolean hasKey = redisTemplate.hasKey(token);

            if (hasKey){
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }


    }

    @Override
    public void destroy() {

    }
}
